'use strict';

//导入模块；
var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');

var root = path.resolve(process.argv[2] || '.');
console.log('Static root dir:' + root);

//创建http server， 并传入回调函数；
var server = http.createServer(function (request, response) {
    //获取url的path   
    var pathname = url.parse(request.url).pathname;

    //获取对应的本地路径
    var filepath = path.join(root, pathname);
    //获取文件状态
    fs.stat(filepath, function (err, stats) {
        if (!err && stats.isFile()) {
            //文件存在且未出错
            console.log('200' + request.url);
            //发送200请求
            response.writeHead(200);
            //将文件流导向response
            fs.createReadStream(filepath).pipe(response);
        } else {
            //出错或者文件不存在
            console.log('404' + filepath + request.url);
            //发送404请求
            response.writeHead(404);
            response.end('404 Not Found');
        }
    });
});
server.listen(8080);
console.log('Serevr is running at http://127.0.0.1:8080/');
